package cn.tedu.pic.service

import java.io.File
import java.util.UUID

import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile

import cn.tedu.common.pojo.PicUploadResult
import cn.tedu.common.utils.UploadUtil
import cn.tedu.staticResources.ComRe

@Service
class PicService(){

  def picUpload(pic: MultipartFile) = {
    val result = new PicUploadResult()
    /*1 .获取后缀判断合法 .jpg .png .gif/docx,txt
		 *2 .生成路径 upload/2/3/4/d/5/d/3/2
		 * D:/img/upload/2/6/4/a/a/5/2/3
		 *image.jt.com/upload/\2\6\4\a\a\5\2\3
		 *3 .目录结构创建出来File
		 *4 .重新定义文件名称,拼接到url地址,和path生成路径
		 *5 .封装数据picUploadResult对象的url返回
		 *6 .流输出到磁盘
		 */
    //拿到原名称 penguin.jpg
    val oName = pic getOriginalFilename
    //截取后缀
    val extName = oName.split("\\.").last
    //判断
    if (!extName.matches(".(png|jpg|gif)")) { //后缀非法
      result setError 1
      result
    }
    val dir = UploadUtil.getUploadPath(oName, "upload") + "/"
    //dir=///upload\2\6\4\a\a\5\2\3
    val path = ComRe.path_pre + dir
    //d://img//upload\2\6\4\a\a\5\2\3
    val urlPath = ComRe.urlPath_pre + dir
    //http://image.jt.com//upload\2\6\4\a\a\5\2\3
    //重命名文件,唯一的名称uuid
    val fileName = UUID.randomUUID.toString + extName
    //fileName=1212-234ndlwjhfq2-324l2314.jpg
    //创建文件夹path,将图片输出到这个目录中
    val _dir = new File(path) //判断目录是否存在
    if (!_dir.exists) {
      //创建目录
      _dir.mkdirs
    }
    //输出到目录中

    try {
      pic transferTo new File(path + fileName)
      //d://img//upload\2\6\4\a\a\5\2\3\1212-234ndlwjhfq2-324l2314.jpg
      result setUrl (urlPath + fileName)
    } catch {
      case t: Throwable =>
        t.printStackTrace()
        result setError 1; result
    }
    result
  }

}